import 'dart:developer' as developer;
import 'dart:async';
import 'package:azring/core/models/ring_sport_record.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../services/ring_service.dart';
import '../../services/device_storage_service.dart';
import '../repository/default_api.dart';

/// 戒指控制器
/// 负责管理戒指相关的业务逻辑和UI状态
class RingController extends GetxController {
  static const String _tag = 'RingController';

  // 获取戒指服务实例
  late final RingService _ringService;
  late final DeviceStorageService _deviceStorage;

  // UI状态变量
  final RxBool _isLoading = false.obs;
  final RxString _statusMessage = '未连接'.obs;

  // Getters
  bool get isLoading => _isLoading.value;
  String get statusMessage => _statusMessage.value;

  // 戒指服务数据的便捷访问
  List<RingDevice> get scannedDevices => _ringService.scannedDevices;
  RingDevice? get connectedDevice => _ringService.connectedDevice;
  StepsData? get stepsData => _ringService.stepsData;
  SleepData? get sleepData => _ringService.sleepData;
  Rx<SleepData?> get sleepDataRx => _ringService.sleepDataRx;
  int get heartRate => _ringService.heartRate;
  int get battery => _ringService.battery;
  bool get isCharging => _ringService.isCharging; // 是否正在充电
  RxInt get batteryRx => _ringService.batteryRx;
  RxBool get isChargingRx => _ringService.isChargingRx; // 充电状态的响应式访问器
  bool get isScanning => _ringService.isScanning;
  bool get isConnected => _ringService.isConnected;
  RingConnectionState get connectionState => _ringService.connectionState;

  // 新增数据的便捷访问
  BloodOxygenData? get bloodOxygenData => _ringService.bloodOxygenData;
  HrvData? get hrvData => _ringService.hrvData;
  StressData? get stressData => _ringService.stressData;
  HeartRateData? get heartRateData => _ringService.heartRateData;
  HistoryHeartRateData? get historyHeartRateData =>
      _ringService.historyHeartRateData;
  RingSportRecord? get sportRecord => _ringService.sportRecord;

  // 测量状态
  bool get isHeartRateMeasuring => _ringService.isHeartRateMeasuring;
  bool get isBloodOxygenMeasuring => _ringService.isBloodOxygenMeasuring;
  bool get isHrvMeasuring => _ringService.isHrvMeasuring;
  bool get isStressMeasuring => _ringService.isStressMeasuring;

  // 响应式数据访问
  Rx<BloodOxygenData?> get bloodOxygenDataRx => _ringService.bloodOxygenDataRx;
  Rx<HrvData?> get hrvDataRx => _ringService.hrvDataRx;
  Rx<StressData?> get stressDataRx => _ringService.stressDataRx;
  Rx<HeartRateData?> get heartRateDataRx => _ringService.heartRateDataRx;
  Rx<HistoryHeartRateData?> get historyHeartRateDataRx =>
      _ringService.historyHeartRateDataRx;
  Rx<RingSportRecord?> get sportRecordRx => _ringService.sportRecordRx;
  RxList<int?> get todayStressListRx => _ringService.todayStressListRx;

  @override
  void onInit() {
    super.onInit();
    _initializeRingService();
    _setupStatusListener();
    developer.log('🎮 戒指控制器初始化完成', name: _tag);
  }

  /// 初始化戒指服务
  void _initializeRingService() {
    try {
      _ringService = Get.find<RingService>();
      _deviceStorage = Get.find<DeviceStorageService>();
    } catch (e) {
      developer.log('❌ 初始化戒指服务失败: $e', name: _tag);
      // 如果找不到服务，尝试重新注册
      try {
        _ringService = Get.put<RingService>(RingService(), permanent: true);
        _deviceStorage = Get.put<DeviceStorageService>(DeviceStorageService(),
            permanent: true);
        developer.log('🔄 已重新注册戒指服务', name: _tag);
      } catch (e2) {
        developer.log('❌ 重新注册戒指服务失败: $e2', name: _tag);
      }
    }
  }

  /// 设置状态监听器
  void _setupStatusListener() {
    // 监听连接状态变化
    ever(_ringService.connectionStateRx, (RingConnectionState state) {
      _updateStatusMessage(state);

      // 连接成功后自动获取设备信息
      if (state == RingConnectionState.connected) {
        _onDeviceConnected();
      }
    });
  }
 

  /// 更新状态消息
  void _updateStatusMessage(RingConnectionState state) {
    switch (state) {
      case RingConnectionState.disconnected:
        _statusMessage.value = '未连接';
        break;
      case RingConnectionState.connecting:
        _statusMessage.value = '连接中...';
        break;
      case RingConnectionState.connected:
        _statusMessage.value = '已连接';
        break;
    }
  }

  /// 设备连接成功后的处理
  Future<void> _onDeviceConnected() async {
    try {
      developer.log('🎉 设备连接成功，开始获取设备信息', name: _tag);

      // 【移除】不再手动调用 fetchAllDeviceData()
      // Kotlin 端在连接成功后会自动调用 fetchAllDeviceData()
      // 避免重复调用导致睡眠数据被查询两次
      developer.log('✅ 连接成功，等待 Kotlin 端自动获取数据', name: _tag);
    } catch (e) {
      developer.log('❌ 获取设备信息异常: $e', name: _tag);
    }
  }

  /// 扫描戒指设备
  Future<void> scanDevices() async {
    try {
      _setLoading(true);
      developer.log('🔍 开始扫描戒指设备', name: _tag);

      final success = await _ringService.startScan();
      if (!success) {
        _showError('扫描失败，请检查蓝牙权限');
      }
    } catch (e) {
      developer.log('❌ 扫描异常: $e', name: _tag);
      _showError('扫描异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 停止扫描
  Future<void> stopScan() async {
    try {
      developer.log('⏹️ 停止扫描', name: _tag);
      await _ringService.stopScan();
    } catch (e) {
      developer.log('❌ 停止扫描异常: $e', name: _tag);
    }
  }

  /// 连接指定设备
  Future<void> connectDevice(RingDevice device) async {
    try {
      _setLoading(true);
      developer.log('🔗 连接设备: ${device.name}', name: _tag);

      final success = await _ringService.connectDevice(device);
      if (success) {
        _showSuccess('正在连接设备...');
      } else {
        _showError('连接失败');
      }
    } catch (e) {
      developer.log('❌ 连接异常: $e', name: _tag);
      _showError('连接异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 断开设备连接（保留设备信息以便自动重连）
  Future<void> disconnectDevice() async {
    try {
      _setLoading(true);
      developer.log('🔌 断开设备连接', name: _tag);

      final success = await _ringService.disconnectDevice();
      if (success) {
        _showSuccess('设备已断开连接，设备信息已保留');
      } else {
        _showError('断开连接失败');
      }
    } catch (e) {
      developer.log('❌ 断开连接异常: $e', name: _tag);
      _showError('断开连接异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 解绑设备（断开连接并清除设备信息）
  Future<void> unbindDevice() async {
    try {
      _setLoading(true);
      developer.log('🗑️ 解绑设备', name: _tag);

      final success = await _ringService.unbindDevice();
      if (success) {
        _showSuccess('设备已解绑');
      } else {
        _showError('解绑设备失败');
      }
    } catch (e) {
      developer.log('❌ 解绑设备异常: $e', name: _tag);
      _showError('解绑设备异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取步数数据
  Future<void> fetchStepsData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('👟 获取步数数据', name: _tag);

      final success = await _ringService.queryCurrentSteps();
      if (!success) {
        _showError('获取步数数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取步数数据异常: $e', name: _tag);
      _showError('获取步数数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取睡眠数据
  Future<void> fetchSleepData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('😴 获取睡眠数据', name: _tag);

      final success = await _ringService.querySleep();
      if (!success) {
        _showError('获取睡眠数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取睡眠数据异常: $e', name: _tag);
      _showError('获取睡眠数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取心率数据
  Future<void> fetchHeartRateData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('❤️ 获取心率数据', name: _tag);

      final success = await _ringService.queryHeartRate();
      if (!success) {
        _showError('获取心率数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取心率数据异常: $e', name: _tag);
      _showError('获取心率数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取历史心率数据
  Future<void> fetchHistoryHeartRateData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📊 获取历史心率数据', name: _tag);

      final success = await _ringService.queryHeartRate();
      if (!success) {
        _showError('获取历史心率数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取历史心率数据异常: $e', name: _tag);
      _showError('获取历史心率数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取电池电量
  Future<void> fetchBatteryData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('🔋 获取电池电量', name: _tag);

      final success = await _ringService.queryBattery();
      if (!success) {
        _showError('获取电池电量失败');
      }
    } catch (e) {
      developer.log('❌ 获取电池电量异常: $e', name: _tag);
      _showError('获取电池电量异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 开始心率测量
  Future<void> startHeartRateMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('💓 开始心率测量', name: _tag);

      final success = await _ringService.startHeartRateMeasure();
      if (success) {
        _showSuccess('心率测量已开始');
      } else {
        _showError('开始心率测量失败');
      }
    } catch (e) {
      developer.log('❌ 开始心率测量异常: $e', name: _tag);
      _showError('开始心率测量异常: $e');
    }
  }

  /// 停止心率测量
  Future<void> stopHeartRateMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏹️ 停止心率测量', name: _tag);

      final success = await _ringService.stopHeartRateMeasure();
      if (success) {
        _showSuccess('心率测量已停止');

        // 停止测量后，延迟一点时间然后获取最新的心率数据
        await Future.delayed(const Duration(milliseconds: 500));
        await fetchHeartRateData();
      } else {
        _showError('停止心率测量失败');
      }
    } catch (e) {
      developer.log('❌ 停止心率测量异常: $e', name: _tag);
      _showError('停止心率测量异常: $e');
    }
  }

  /// 同步时间
  Future<void> syncTime() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('⏰ 同步时间', name: _tag);

      final success = await _ringService.syncTime();
      if (success) {
        _showSuccess('时间同步成功');
      } else {
        _showError('时间同步失败');
      }
    } catch (e) {
      developer.log('❌ 同步时间异常: $e', name: _tag);
      _showError('同步时间异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取血氧数据
  Future<void> fetchBloodOxygenData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('🩸 获取血氧数据', name: _tag);

      final success = await _ringService.queryBloodOxygen();
      if (!success) {
        _showError('获取血氧数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取血氧数据异常: $e', name: _tag);
      _showError('获取血氧数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 开始血氧测量
  Future<void> startBloodOxygenMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('🩸 开始血氧测量', name: _tag);

      final success = await _ringService.startBloodOxygenMeasure();
      if (success) {
        _showSuccess('血氧测量已开始');
      } else {
        _showError('开始血氧测量失败');
      }
    } catch (e) {
      developer.log('❌ 开始血氧测量异常: $e', name: _tag);
      _showError('开始血氧测量异常: $e');
    }
  }

  /// 停止血氧测量
  Future<void> stopBloodOxygenMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏹️ 停止血氧测量', name: _tag);

      final success = await _ringService.stopBloodOxygenMeasure();
      if (success) {
        _showSuccess('血氧测量已停止');
      } else {
        _showError('停止血氧测量失败');
      }
    } catch (e) {
      developer.log('❌ 停止血氧测量异常: $e', name: _tag);
      _showError('停止血氧测量异常: $e');
    }
  }

  /// 获取HRV数据
  Future<void> fetchHrvData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('🫀 获取HRV数据', name: _tag);

      final success = await _ringService.queryHrv();
      if (!success) {
        _showError('获取HRV数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取HRV数据异常: $e', name: _tag);
      _showError('获取HRV数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 开始HRV测量
  Future<void> startHrvMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('🫀 开始HRV测量', name: _tag);

      final success = await _ringService.startHrvMeasure();
      if (success) {
        _showSuccess('HRV测量已开始');
      } else {
        _showError('开始HRV测量失败');
      }
    } catch (e) {
      developer.log('❌ 开始HRV测量异常: $e', name: _tag);
      _showError('开始HRV测量异常: $e');
    }
  }

  /// 停止HRV测量
  Future<void> stopHrvMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏹️ 停止HRV测量', name: _tag);

      final success = await _ringService.stopHrvMeasure();
      if (success) {
        _showSuccess('HRV测量已停止');

        // 停止测量后，延迟一点时间然后获取最新的HRV数据
        await Future.delayed(const Duration(milliseconds: 500));
        await fetchHrvData();
      } else {
        _showError('停止HRV测量失败');
      }
    } catch (e) {
      developer.log('❌ 停止HRV测量异常: $e', name: _tag);
      _showError('停止HRV测量异常: $e');
    }
  }

  /// 获取压力数据
  Future<void> fetchStressData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('😰 获取压力数据', name: _tag);

      final success = await _ringService.queryStress();
      if (!success) {
        _showError('获取压力数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取压力数据异常: $e', name: _tag);
      _showError('获取压力数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 开始压力测量
  Future<void> startStressMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('😰 开始压力测量', name: _tag);

      final success = await _ringService.startStressMeasure();
      if (success) {
        _showSuccess('压力测量已开始');
      } else {
        _showError('开始压力测量失败');
      }
    } catch (e) {
      developer.log('❌ 开始压力测量异常: $e', name: _tag);
      _showError('开始压力测量异常: $e');
    }
  }

  /// 停止压力测量
  Future<void> stopStressMeasure() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏹️ 停止压力测量', name: _tag);

      final success = await _ringService.stopStressMeasure();
      if (success) {
        _showSuccess('压力测量已停止');
      } else {
        _showError('停止压力测量失败');
      }
    } catch (e) {
      developer.log('❌ 停止压力测量异常: $e', name: _tag);
      _showError('停止压力测量异常: $e');
    }
  }

  /// 发送用户信息
  Future<void> sendUserInfo({
    required int weight,
    required int height,
    required int gender,
    required int age,
    required int stride,
  }) async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('👤 发送用户信息', name: _tag);

      final success = await _ringService.sendUserInfo(
        weight: weight,
        height: height,
        gender: gender,
        age: age,
        stride: stride,
      );
      if (success) {
        _showSuccess('用户信息已发送');
      } else {
        _showError('发送用户信息失败');
      }
    } catch (e) {
      developer.log('❌ 发送用户信息异常: $e', name: _tag);
      _showError('发送用户信息异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取所有设备数据（调用Android端自动获取7类数据的方法）
  Future<void> fetchAllDeviceData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📊 手动获取所有设备数据 (7类数据)', name: _tag);

      final success = await _ringService.fetchAllDeviceData();
      if (success) {
        _showSuccess('数据获取请求已发送');
      } else {
        _showError('数据获取请求失败');
      }
    } catch (e) {
      developer.log('❌ 获取所有设备数据异常: $e', name: _tag);
      _showError('获取数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 获取所有数据
  Future<void> fetchAllData() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📊 获取所有戒指数据', name: _tag);

      await _ringService.fetchAllData();
      _showSuccess('数据同步完成');
    } catch (e) {
      developer.log('❌ 获取所有数据异常: $e', name: _tag);
      _showError('获取数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 刷新设备状态
  Future<void> refreshDeviceStatus() async {
    try {
      developer.log('🔄 刷新设备状态', name: _tag);

      if (isConnected) {
        await fetchAllData();
      }
    } catch (e) {
      developer.log('❌ 刷新状态异常: $e', name: _tag);
    }
  }

  /// 检查设备连接状态
  bool _checkConnection() {
    if (!isConnected) {
      _showError('设备未连接');
      return false;
    }
    return true;
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading.value = loading;
  }

  /// 显示成功消息
  void _showSuccess(String message) {
    // 根据用户要求，接口调用成功不显示弹窗
    // Toast.show(message);
  }

  /// 显示错误消息
  void _showError(String message) {
    Toast.show(message);
  }

  /// 格式化步数显示
  String getFormattedSteps() {
    final steps = stepsData?.steps ?? 0;
    if (steps >= 10000) {
      return '${(steps / 1000).toStringAsFixed(1)}k';
    }
    return steps.toString();
  }

  /// 格式化距离显示
  String getFormattedDistance() {
    final distance = stepsData?.distance ?? 0;
    if (distance >= 1000) {
      return '${(distance / 1000).toStringAsFixed(1)}km';
    }
    return '${distance}m';
  }

  /// 格式化卡路里显示
  String getFormattedCalories() {
    final calories = stepsData?.calories ?? 0;
    return '${calories}cal';
  }

  /// 格式化睡眠时间显示
  String getFormattedSleepTime() {
    final totalMinutes = sleepData?.totalSleepTime ?? 0;
    final hours = totalMinutes ~/ 60;
    final minutes = totalMinutes % 60;
    return '${hours}h ${minutes}m';
  }

  /// 获取心率状态
  String getHeartRateStatus() {
    if (heartRate == 0) return '未测量';
    if (heartRate < 60) return '偏低';
    if (heartRate > 100) return '偏高';
    return '正常';
  }

  /// 获取电池状态
  String getBatteryStatus() {
    if (isCharging) return '充电中';
    if (battery == 0) return '未知';
    if (battery < 20) return '低电量';
    if (battery < 50) return '中等';
    return '充足';
  }

  /// 获取当前连接设备的 deviceSn
  ///
  /// 返回当前连接设备的序列号，如果未连接则返回空字符串
  String getCurrentDeviceSn() {
    return _ringService.getCurrentDeviceSn();
  }

  /// 获取当前连接设备的完整信息
  ///
  /// 返回当前连接设备的完整信息，包括 deviceSn
  RingDevice? getCurrentDevice() {
    return _ringService.getCurrentDevice();
  }

  /// 检查是否有连接的设备
  bool get hasConnectedDevice => isConnected && getCurrentDeviceSn().isNotEmpty;

  /// 发送运动明细数据到接口
  Future<void> sendSportDetailToApi({
    required String deviceSn,
    required String historyDay,
    required List<int> stepsList,
  }) async {
    try {
      developer.log('📤 控制器开始发送运动明细数据到接口', name: _tag);

      if (!isConnected) {
        _showError('设备未连接，无法发送运动明细数据');
        return;
      }

      await _ringService.sendSportDetailToApi(
        deviceSn: deviceSn,
        historyDay: historyDay,
        stepsList: stepsList,
      );

      _showSuccess('运动明细数据发送成功');
    } catch (e) {
      developer.log('❌ 控制器发送运动明细数据失败: $e', name: _tag);
      _showError('发送运动明细数据失败: $e');
    }
  }

  /// 发送今日运动明细数据到接口
  Future<void> sendTodaySportDetailToApi({
    required String deviceSn,
    required List<int> stepsList,
  }) async {
    final today = DateTime.now();
    final historyDay =
        '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';

    await sendSportDetailToApi(
      deviceSn: deviceSn,
      historyDay: historyDay,
      stepsList: stepsList,
    );
  }

  /// 获取今日压力列表数据
  Future<void> fetchTodayStressList() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📊 获取今日压力列表数据', name: _tag);

      final success = await _ringService.queryTodayStressList();
      if (!success) {
        _showError('获取今日压力列表数据失败');
      }
    } catch (e) {
      developer.log('❌ 获取今日压力列表数据异常: $e', name: _tag);
      _showError('获取今日压力列表数据异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  // ==================== 训练功能 ====================

  /// 查询支持的训练类型
  Future<void> querySupportTraining() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('🏃 查询支持的训练类型', name: _tag);

      final success = await _ringService.querySupportTraining();
      if (!success) {
        _showError('查询训练类型失败');
      }
    } catch (e) {
      developer.log('❌ 查询训练类型异常: $e', name: _tag);
      _showError('查询训练类型异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 开始训练
  Future<void> startTraining({
    required String type,
    int? caloriesGoal,
    int? durationGoal,
    int? distanceGoal,
  }) async {
    if (!_checkConnection()) return;

    try {
      developer.log('🏃 开始训练: type=$type', name: _tag);

      final success = await _ringService.startTraining(
        type: type,
        caloriesGoal: caloriesGoal,
        durationGoal: durationGoal,
        distanceGoal: distanceGoal,
      );
      if (success) {
        _showSuccess('训练已开始');
      } else {
        _showError('开始训练失败');
      }
    } catch (e) {
      developer.log('❌ 开始训练异常: $e', name: _tag);
      _showError('开始训练异常: $e');
    }
  }

  /// 暂停训练
  Future<void> pauseTraining() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏸️ 暂停训练', name: _tag);

      final success = await _ringService.pauseTraining();
      if (success) {
        _showSuccess('训练已暂停');
      } else {
        _showError('暂停训练失败');
      }
    } catch (e) {
      developer.log('❌ 暂停训练异常: $e', name: _tag);
      _showError('暂停训练异常: $e');
    }
  }

  /// 继续训练
  Future<void> resumeTraining() async {
    if (!_checkConnection()) return;

    try {
      developer.log('▶️ 继续训练', name: _tag);

      final success = await _ringService.resumeTraining();
      if (success) {
        _showSuccess('训练已继续');
      } else {
        _showError('继续训练失败');
      }
    } catch (e) {
      developer.log('❌ 继续训练异常: $e', name: _tag);
      _showError('继续训练异常: $e');
    }
  }

  /// 结束训练
  Future<void> endTraining() async {
    if (!_checkConnection()) return;

    try {
      developer.log('⏹️ 结束训练', name: _tag);

      final success = await _ringService.endTraining();
      if (success) {
        _showSuccess('训练已结束');
      } else {
        _showError('结束训练失败');
      }
    } catch (e) {
      developer.log('❌ 结束训练异常: $e', name: _tag);
      _showError('结束训练异常: $e');
    }
  }

  /// 查询训练状态
  Future<void> queryTrainingState() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('🏃 查询训练状态', name: _tag);

      final success = await _ringService.queryTrainingState();
      if (!success) {
        _showError('查询训练状态失败');
      }
    } catch (e) {
      developer.log('❌ 查询训练状态异常: $e', name: _tag);
      _showError('查询训练状态异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 查询历史训练记录
  Future<void> queryHistoryTraining() async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📋 查询历史训练记录', name: _tag);

      final success = await _ringService.queryHistoryTraining();
      if (!success) {
        _showError('查询历史训练记录失败');
      }
    } catch (e) {
      developer.log('❌ 查询历史训练记录异常: $e', name: _tag);
      _showError('查询历史训练记录异常: $e');
    } finally {
      _setLoading(false);
    }
  }

  /// 根据ID查询训练详情
  Future<void> queryTrainingById(int id) async {
    if (!_checkConnection()) return;

    try {
      _setLoading(true);
      developer.log('📋 查询训练详情: id=$id', name: _tag);

      final success = await _ringService.queryTrainingById(id);
      if (!success) {
        _showError('查询训练详情失败');
      }
    } catch (e) {
      developer.log('❌ 查询训练详情异常: $e', name: _tag);
      _showError('查询训练详情异常: $e');
    } finally {
      _setLoading(false);
    }
  }

}
